package com.gcxy.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcxy.config.result.PageVO;
import com.gcxy.config.result.R;
import com.gcxy.domain.dto.*;
import com.gcxy.entity.User;
import com.gcxy.mapper.UserMapper;
import com.gcxy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public R login(loginDto loginDto) {
        // 查询用户信息，状态为启用
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getAccount, loginDto.getAccount());
        User user = this.getOne(userWrapper);
        // 用户是否存在
        if (user == null) {
            return R.Failed("账户不存在");
        }
        // 判断用户状态
        if (user.getStatus() == 0) {
            return R.Failed("账户被禁用,无法登录，请联系管理员");
        }
        // 加密并验证密码
        String pwd = DigestUtils.md5Hex(loginDto.getPassword());
        if (!user.getPassword().equals(pwd)) {
            return R.Failed("密码错误");
        }
        // 登录
        StpUtil.login(user.getAccount());
        // 获取 Token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return R.Success(tokenInfo.getTokenValue());
    }

    @Override
    public R logout() {
//        1.先获取当前用户的 token
        String currentToken = StpUtil.getTokenValue();
//        2.判断 token 是否存在
        if (currentToken == null) {
            return R.Failed("当前用户未登录");
        }
//        3.然后注销登录
        StpUtil.logoutByTokenValue(currentToken);
//        3.返回成功信息
        return R.Success("退出成功");
    }

    //添加用户
    @Override
    public R addUser(AddUserDTO addUserDTO) {
        String phone = addUserDTO.getPhone();
        //校验手机号是否为数字
        if (!phone.matches("\\d{11}")) {
            return R.Failed("手机号格式不正确");
        }
        QueryWrapper<User> userManageQueryWrapper = new QueryWrapper<>();
        userManageQueryWrapper.eq("phone", phone);
        User user = userMapper.selectOne(userManageQueryWrapper);
        if (user != null) {
            return R.Failed("手机号已存在");
        } else {
            User user1 = new User();
            BeanUtils.copyProperties(addUserDTO, user1);
            user1.setStatus(1);
            user1.setRole(0);//0用户 1管理员
            userMapper.insert(user1);
            return R.Success("添加成功");
        }
    }

    ///修改用户
    @Override
    public R updateUser(UpdateUserDTO updateUserDTO) {
        String phone = updateUserDTO.getPhone();
        String password = updateUserDTO.getPassword();
        String email = updateUserDTO.getEmail();

        //根据id查询用户是否存在
        int id = updateUserDTO.getId();
        User byId = getById(id);
        if (byId == null) {
            return R.Failed("用户不存在");
        }
        //排除自己电话号
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phone).ne("id", id);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user != null) {
            return R.Failed("手机号已存在");
        }
        //排除自己的邮箱
        QueryWrapper<User> userEmailQueryWrapper = new QueryWrapper<>();
        userEmailQueryWrapper.eq("email", email).ne("id", id);
        User userEmail = userMapper.selectOne(userEmailQueryWrapper);
        if (userEmail != null) {
            return R.Failed("邮箱已存在");
        }

        User user1 = new User();
        BeanUtils.copyProperties(updateUserDTO, user1);
        if (phone == null || phone.isEmpty()) {
            user1.setPhone(byId.getPhone());
        }
        if (password != null && !password.isEmpty()) {
            user1.setPassword(byId.getPassword());
        }
        if (email == null || email.isEmpty()) {
            user1.setEmail(byId.getEmail());
        }
        userMapper.updateById(user1);
        return R.Success("修改成功");

    }

    //获取用户详情
    @Override
    public R getUserDetail(int id) {
        User byId = getById(id);
        if (byId == null) {
            return R.Failed("用户不存在");
        }
        return R.Success(byId);
    }

    //获取用户列表
    @Override
    public R getUserList() {
        List<User> users = userMapper.selectList(null);
        return R.Success(users);
    }

    //分页获取用户列表
    @Override
    public R getUserPage(UserPageDTO userPageDTO) {
        LambdaQueryWrapper<User> userManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userManageLambdaQueryWrapper
                .like(userPageDTO.getAccount() != null, User::getAccount, userPageDTO.getAccount())
                .like(userPageDTO.getPhone() != null, User::getPhone, userPageDTO.getPhone());
        //分页查询
        Page<User> userManagePage = new Page<>(userPageDTO.getPageNumber(), userPageDTO.getPageSize());
        userManagePage = userMapper.selectPage(userManagePage, userManageLambdaQueryWrapper);
        //转换成PageVO
        PageVO<User> userManagePageVO = new PageVO<>();
        BeanUtils.copyProperties(userManagePage, userManagePageVO);
        List<User> records = userManagePage.getRecords();
        userManagePageVO.setRecords(records);

        if (userManagePageVO.getTotal() == null) {
            return R.Failed("未查询到用户信息");
        } else {
            return R.Success("查询成功", userManagePageVO);
        }
    }

    @Override
    public List<Integer> getIds(GetIdDTO getIdDTO) {
        LambdaQueryWrapper<User> userManageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userManageLambdaQueryWrapper
                .like(getIdDTO.getAccount() != null, User::getAccount, getIdDTO.getAccount())
                .like(getIdDTO.getPhone() != null, User::getPhone, getIdDTO.getPhone());

        List<User> users = userMapper.selectList(userManageLambdaQueryWrapper);
        List<Integer> ids = users.stream().map(User::getId).toList();
        return ids;
    }
}
